package com.sea.app.module.identity.domain.service;

import com.sea.app.common.kit.Dates;
import com.sea.app.module.identity.domain.User;
import com.sea.app.module.identity.domain.algorithm.Login;
import com.sea.app.module.identity.domain.repository.UserRepository;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * Created by 31417 on 2017/4/26.
 */
@Service
public class AuthService {
    @Value("${security.key}")
    private String key;

    @Autowired
    UserRepository userRepository;

    /**
     * 授权登录
     * @param loginName
     * @param password
     * @return 登录后的令牌
     */
    public String login(String loginName,String password,String ip ){
        User user = userRepository.findByLoginName(loginName);
        Login.on(user).login(password);
        return Jwts.builder()
                .setClaims(new HashMap<String,Object>(){{
                    put("roles",user.getRoles().stream().map(role -> role.getCode()).collect(Collectors.toList()));
                    put("name",user.getName());
                    put("avater",user.getAvatar());
                    put("ip",ip);
                }})
                .setId(user.getId().toString())
                .setSubject(user.getLoginName())
                .setIssuedAt(Dates.now())
                .setExpiration(Dates.now().addDay(15))
                .signWith(SignatureAlgorithm.HS512, key)
                .compact();
    }
}
